package com.gpnu.crm.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gpnu.crm.domain.Employee;
import com.gpnu.crm.service.IEmployeeService;

@Component("realm")
public class CRMRealm extends AuthorizingRealm {
	@Autowired
	private IEmployeeService employeeService;

	@Autowired
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		super.setCredentialsMatcher(credentialsMatcher);
	}

	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		Employee emp = this.employeeService.getByUsername(upToken.getUsername());

		if (emp == null) {
			return null;
		}

		return new SimpleAuthenticationInfo(emp, emp.getPassword(), ByteSource.Util.bytes(emp.getName()), getName());
	}

	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Employee emp = (Employee) principals.getPrimaryPrincipal();

		if (emp.isAdmin()) {
			System.out.println("ADMIN");
			info.addRole("admin");
			info.addStringPermission("*:*");
		} else {
			List<String> roles = this.employeeService.getRoleNamesByEmployeeId(emp.getId());
			List<String> permissions = this.employeeService.getPermissionsByEmployeeId(emp.getId());
			info.addRoles(roles);
			info.addStringPermissions(permissions);
		}
		return info;
	}
}
